package com.stedu.mall.goodsservice.controller;

import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Goods;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.MallException;
import com.stedu.mall.common.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    //添加
    @PostMapping
    public RespBean insert(@RequestBody Goods goods) throws MallException {
        goods.setScore(5f);
        goodsService.insert(goods);

        return RespBean.ok("添加成功");
    }
    //根据id删除
    @DeleteMapping(("/{id}"))
    public RespBean delete(@PathVariable("id") Integer id) throws MallException {
        goodsService.delete(id);

        return RespBean.ok("删除成功");
    }
    //根据id修改
    @PutMapping
    public RespBean update(@RequestBody Goods goods) throws MallException {
        goodsService.update(goods);

        return RespBean.ok("修改成功");
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (Goods condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 5 : pageSize;

        PageInfo<Goods> pageInfo = goodsService.selectByCondition(condition, pageNum, pageSize);

        return RespBean.ok("",pageInfo);
    }
    @GetMapping("/search")
    public RespBean selectByPage1 (Goods condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 5 : pageSize;

        PageInfo<Goods> pageInfo = goodsService.selectByCondition1(condition, pageNum, pageSize);

        return RespBean.ok("",pageInfo);
    }
    //根据id查询
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        return RespBean.ok("",goodsService.selectById(id));
    }

    //热门商品前5
    @GetMapping("/goodsTop5")
    public RespBean goodsTop5(){

        List<Map<String, Object>> list = goodsService.goodsSaleTop5();

        return RespBean.ok("",list);
    }
}
